//
//  HRLocationManager.m
//  原生定位和地理编码
//
//  Created by Hello Cai on 2021/8/5.
//

#import "HRLocationManager.h"

@interface HRLocationManager()<CLLocationManagerDelegate>

@property(nonatomic, strong)CLLocationManager *locationManager;

@property (nonatomic, copy) LocationSuccess locationSuccess;
@property (nonatomic, copy) LocationFail locationFail;

@end

@implementation HRLocationManager

+(instancetype)sharedInstance{
    static id _manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [[HRLocationManager alloc] init];
        
    });
    return _manager;
}


-(void)startLocation:(LocationSuccess)success failure:(LocationFail)failure {
    self.locationSuccess = success;
    self.locationFail = failure;
    [self.locationManager startUpdatingLocation];
}


#pragma mark - CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    if (self.locationSuccess) {
        self.locationSuccess(locations.lastObject);
    }
    [self.locationManager stopUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    //iOS14系统在弹出授权定位弹窗，用户未选择任何选项的情况下会回调到该代理方法中，这是苹果的Bug，过滤掉
    //如果用户选择的是“不允许”，也会回调该方法，但authorizationStatus的值为kCLAuthorizationStatusDenied
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        return;
    }
//    NSLog(@"error:%@", error);
    if (self.locationFail) {
        self.locationFail(manager, error);
    }
}


-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        //请求前台、后台定位授权
        /*
          info.plist必须设置
          NSLocationAlwaysAndWhenInUseUsageDescription、NSLocationWhenInUseUsageDescription
         */
        [_locationManager requestAlwaysAuthorization];
        
        //请求前台定位授权
        /*
          info.plist必须设置NSLocationWhenInUseUsageDescription
          如果想要后台也能获得定位，Signing & Capabilities->Backgroud Modes要勾选Location updates，且iOS9以上必须设置allowsBackgroundLocationUpdates为YES
         */
//        [_locationManager requestWhenInUseAuthorization];
//        if (@available(iOS 9.0, *)) {
//            _locationManager.allowsBackgroundLocationUpdates = YES;
//        }
    }
    return _locationManager;
}

@end
